package com.example.myapplication;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //外部存储写入
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeToExternalFile("mjt.txt","我的外部数据写入");
            }
        });
        //外部存储读取
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readFromExternalFile("mjt.txt");
            }
        });
    }

    // 写入文件
    public void writeToExternalFile(String fileName, String data) {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        Log.e("mjt","写入文件externalStorageDirectory " + externalStorageDirectory);
        File file = new File(externalStorageDirectory, fileName);
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件
    public String readFromExternalFile(String fileName) {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        Log.e("mjt","读取文件externalStorageDirectory " + externalStorageDirectory);
        File file = new File(externalStorageDirectory, fileName);
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.e("mjt", "readData = " + contentBuilder);
        return contentBuilder.toString();
    }

}